<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <span class="filter-label">注册时间</span>
      <el-date-picker v-model="listQuery.timeRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"/>
      <span class="filter-label">付费筛选</span>
      <el-select v-model="listQuery.is_pay_user" placeholder="用户状态" clearable style="width: 120px" class="filter-item" >
        <el-option v-for="item in userPayStatusOptions" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <span class="filter-label">用户类型</span>
      <el-select v-model="listQuery.account_type" placeholder="用户类型" clearable style="width: 120px" class="filter-item" >
        <el-option v-for="item in userTypeOptions" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <!-- <el-checkbox v-model="listQuery.showRobotData" class="filter-item" style="margin:0 15px;" >
        是否机器人
      </el-checkbox> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAddRobot">
        添加机器人
      </el-button>
      <el-button class="filter-item" type="primary" @click="handleBindFriends">
        批量绑好友
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="用户信息" width="100">
        <template slot-scope="scope">
          <div class="user-box">
            <wish-image :src="scope.row.small_avatar_url" radius="100" width="45" height="45" />
            <p class="user-name">{{ scope.row.nick_name }}</p>
            <p class="user-id">{{ scope.row.user_id }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.register_time }}
        </template>
      </el-table-column>
      <el-table-column label="余额" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.wish_coin_num }}
        </template>
      </el-table-column>
      <el-table-column label="发起次数" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.initiate_num }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="帮付款次数" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.pay_num }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="累计付款金额" width="200">
        <template slot-scope="scope">
          {{ scope.row.pay_money_total }}
        </template>
      </el-table-column>
      <el-table-column label="累计消耗心愿值" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.pageviews }}
        </template>
      </el-table-column>
      <el-table-column label="当前未完成心愿" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.pageviews }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="210" align="center">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" style="marginBottom:10px" @click="onUpdateInfo(row)">
            修改信息
          </el-button>
          <el-button type="primary" size="mini" style="marginBottom:10px" @click="onRowBindFriends(row)">
            添加好友
          </el-button>
          <el-button type="danger" size="mini" style="marginBottom:10px" @click="updateAccount(row)">
            修改心愿值
          </el-button>
          <el-button type="danger" size="mini" @click="unBindUser(row)">
            注销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.page_size" @pagination="fetchData"/>
    <!--新增机器人-->
    <el-dialog title="新增机器人" :visible.sync="addRobotVisible" width="500px" custom-class="robot-dialog" destroy-on-close :close-on-click-modal="false" @close="onRobotClose">
      <el-form ref="addRobotForm" :model="addRobotForm" :rules="addRobotFormRules" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar_url">
              <wish-upload v-model="addRobotForm.avatar_url" class="avatar-uploader" path="user/avatar" :list="false" >
                <img v-if="addRobotForm.avatar_url" :src="addRobotForm.avatar_url" class="avatar" >
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </wish-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="addRobotForm.gender" placeholder="性别">
                <el-option v-for="item in sexyOptions" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="昵称" prop="nick_name">
              <el-input v-model="addRobotForm.nick_name"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRobotVisible = false">取消</el-button>
        <el-button type="primary" @click="addRobot">确认</el-button>
      </span>
    </el-dialog>
    <!--修改用户信息-->
    <el-dialog title="修改用户信息" :visible.sync="userDialogVisible" width="500px" custom-class="robot-dialog" destroy-on-close :close-on-click-modal="false" @close="onUserClose">
      <el-form ref="userForm" :model="userForm" :rules="userFormRules" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar_url">
              <wish-upload v-model="userForm.avatar_url" class="avatar-uploader" path="user/avatar" :list="false" >
                <img v-if="userForm.avatar_url" :src="userForm.avatar_url" class="avatar" >
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </wish-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="性别">
                <el-option v-for="item in sexyOptions" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmChange">确认</el-button>
      </span>
    </el-dialog>
    <!--好友关系绑定-->
    <el-dialog title="好友绑定" :visible.sync="bindFriendsVisible" width="420px" custom-class="robot-dialog" destroy-on-close :close-on-click-modal="false" @close="onBindFriendsClose">
      <el-form ref="bindFriendsForm" :model="bindFriendsForm" :rules="bindFriendsFormRules" label-position="top">
        <el-form-item :label="`请输入需要${singleBind?'为其添加':'互绑'}好友的用户ID，ID之间用英文逗号隔开`" prop="friend_str">
          <el-input v-model="bindFriendsForm.friend_str" :autosize="{ minRows: 4}" type="textarea"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindFriendsVisible = false">取消</el-button>
        <el-button type="primary" @click="bindFriends">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { objRemove, mergeObj } from '@/utils'
import { getUserList, addRobot, updateUser, updateUserAccount, unBind, bindFriends } from '@/api/user'
import WishImage from '@/components/Image'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { userTypeOptions, userPayStatusOptions, sexyOptions } from '@/constant/options'
import WishUpload from '@/components/Upload'
export default {
  name: 'UserManage',
  components: { WishImage, Pagination, WishUpload },
  data() {
    const checkUserFriend_str = (rule, value, callback) => {
      if (this.singleBind && !value) {
        callback(new Error('请输入用户ID'))
      } else if (!this.singleBind && (!value || value.split(',').length < 2)) {
        callback(new Error('请输入两个以上用户ID'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        is_pay_user: '',
        account_type: '',
        title: undefined,
        showRobotData: false,
        timeRange: []
      },
      sexyOptions: sexyOptions.slice(1),
      userPayStatusOptions,
      total: 10,
      userTypeOptions,
      addRobotVisible: false,
      userDialogVisible: false,
      bindFriendsVisible: false,
      singleBind: false,
      addRobotForm: {
        avatar_url: '',
        gender: '',
        nick_name: ''
      },
      addRobotFormRules: {
        avatar_url: [{ required: true, message: '请上传头像', trigger: 'change' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      },
      bindFriendsForm: {
        friend_str: '',
        user_id: ''
      },
      bindFriendsFormRules: {
        friend_str: [{ required: true, validator: checkUserFriend_str, trigger: 'blur' }]
      },
      userForm: {
        user_id: '',
        account_type: '',
        account_status: '',
        avatar_url: '',
        gender: '',
        nickname: ''
      },
      userFormRules: {
        avatar_url: [{ required: true, message: '请上传头像', trigger: 'change' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const params = objRemove(this.listQuery)
      if (params.timeRange.length > 0) {
        params.start_time = params.timeRange[0]
        params.end_time = params.timeRange[1]
      }
      getUserList(params).then(res => {
        this.list = res.data.data
        this.total = res.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleAddRobot() {
      this.addRobotVisible = true
    },
    addRobot() {
      this.$refs.addRobotForm.validate(async(valid) => {
        if (valid) {
          await addRobot(this.addRobotForm)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.addRobotVisible = false
        } else {
          console.log('valid fail')
        }
      })
    },
    handleBindFriends() {
      this.singleBind = false
      this.bindFriendsVisible = true
    },
    onRowBindFriends(row) {
      this.singleBind = true
      this.bindFriendsForm.user_id = row.user_id
      this.bindFriendsVisible = true
    },
    bindFriends() {
      this.$refs.bindFriendsForm.validate(async(valid) => {
        if (valid) {
          await bindFriends(this.bindFriendsForm)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.bindFriendsVisible = false
        } else {
          console.log('valid fail')
        }
      })
    },
    onUpdateInfo(row) {
      this.userForm = mergeObj(this.userForm, row)
      this.userForm.avatar_url = row.small_avatar_url
      this.userForm.nickname = row.nick_name
      this.userDialogVisible = true
    },
    confirmChange() {
      this.$refs.userForm.validate(async(valid) => {
        if (valid) {
          await updateUser(this.userForm)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.userDialogVisible = false
        } else {
          console.log('valid fail')
        }
      })
    },
    onRobotClose() {
      this.$refs.addRobotForm.resetFields()
      this.addRobotForm = {
        avatar_url: '',
        gender: '',
        nick_name: ''
      }
    },
    onBindFriendsClose() {
      this.$refs.bindFriendsForm.resetFields()
      this.bindFriendsForm = {
        friend_str: '',
        user_id: ''
      }
    },
    onUserClose() {
      this.$refs.userForm.resetFields()
      this.userForm = {
        user_id: '',
        account_type: '',
        account_status: '',
        avatar_url: '',
        gender: '',
        nickname: ''
      }
    },
    handleLogout(row) {
      this.$confirm('确认注销改用户？', '确认注销', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await updateUser({ user_id: row.user_id, account_type: 1, account_status: 3 })
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.fetchData()
      }).catch(() => {
      })
    },
    unBindUser(row) {
      this.$confirm('确认注销该用户？', '确认注销', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await unBind({ user_id: row.user_id })
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.fetchData()
      }).catch(() => {
      })
    },
    updateAccount(row) {
      this.$prompt('请输入需要增加或减少的数值', '修改心愿值', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputType: 'number',
        inputPlaceholder: '正数增加 负数减少',
        closeOnClickModal: false
      }).then(async({ value }) => {
        await updateUserAccount({ user_id: row.user_id, wish_value: value })
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.fetchData()
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .robot-dialog{
  .el-dialog__body{
    padding: 10px 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
}

.dialog-content{
  display: flex;

}
.left-content{
  width: 180px;
  padding-right: 30px;
  border-right:1px solid #bbb;
  max-height: 400px;
  overflow: auto;
}
.right-content{
  flex:1;
  padding: 0px 43px 0px 63px;
  max-height: 400px;
  overflow: auto;
}
.user-box{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .user-name,.user-id{
    font-size: 14px;
    color:#6F6F6F;
  }
}
.formitem-inline{
  display: flex;
  .el-form-item{
    flex:1;
  }
  .el-form-item:not(:last-child){
    margin-right: 30px;
  }
}

.formitem-inline2{
  display: flex;
  .el-form-item{
    flex:1;
  }
  .el-form-item:not(:last-child){
    margin-right: 80px;
  }
  // .float-100{
  //   float: left;
  //   width: 100%;
  // }
}

  /deep/.head-portrait .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .head-portrait .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
</style>
